<template>
  <div class="main-app">
    <el-form ref="form" :model="form" :rules="rules" label-width="600px" style="margin-top: 50px;">
      <el-form-item label="库位名称:" prop="name" style="width: 60%;">
        <el-input v-model="form.name" clearable />
      </el-form-item>
      <el-form-item label="库位容量:" prop="totalCapacity" style="width: 60%;">
        <el-input v-model="form.totalCapacity" type="number" clearable />
      </el-form-item>
    </el-form>
    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" @click="save">提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import {
  saveLocation,
  getWareHouseLocationById,
} from "../../../../api/warehouse";
export default {
  data() {
    return {
      form: {
        name: "",
        totalCapacity: "",
      },
      rules: {
        totalCapacity: [
          { required: true, message: "请输入库位容量", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入库位名称", trigger: "blur" }],
      },
      id: "",
      code: "",
      locationId: ""
    };
  },
  async created() {
    const { id, code } = this.$route.params;
    console.log(code);
    this.id = id;
    this.locationId = id;
    if (code) {
      this.code = code;
      await this.getWareHouseLocationById(code);
    }
  },
  methods: {
    async getWareHouseLocationById(id) {
      const { data } = await getWareHouseLocationById(id);
      console.log(data)
      this.form.name = data.name;
      this.form.totalCapacity = data.totalCapacity.toString();
    },
    save() {
      this.$refs["form"].validate(async(valid) => {
        if (valid) {
          let data = {
            wareHouseId: this.id,
            totalCapacity: this.form.totalCapacity.toString(),
            name: this.form.name,
          };
          let message = "";
          if (!this.code) {
            message = "新增";
          } else {
            data = Object.assign({ id: this.code }, data);
            message = "修改";
          }
          await saveLocation(data);
          this.$notify({
            title: "成功",
            message: `库位${message}成功`,
            type: "success",
            duration: 3000,
          });
          this.$router.push(`/warehouse/location/${this.locationId}`);
        }
      });
    },
    cancel() {
      this.$router.push(`/warehouse/location/${this.locationId}`);
    },
  },
};
</script>
